
var EpyVendor = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    panel: null,
    content: null,
    listData: null,
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        this.createTable();
    },
    createTable: function() {

        this.content = new Element('div#content');

        this.listData = new Element('table#listData', {'rules':'groups'});
        this.panel.adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        )

        this.listData.adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.imgCol[html=&nbsp;]'),
                    new Element('th.imgCol[html=&nbsp;]'),
                    new Element('th.imgCol[text=Active]'),
                    new Element('th.brdCol.center.w50[text=Alias]'),
                    new Element('th.brdCol.w120[text=Vendor name]'),
                    new Element('th.brdCol.center.w50[html=Send to<br/>total-amazon-amzcomp-ebay-ebayA-buycom]'),
                    new Element('th.brdCol.center.w50[html=Amazon<br/>margin-charge-qty]'),
                    new Element('th.brdCol.center.w50[html=AmzComp<br/>margin-charge-qty]'),
                    new Element('th.brdCol.center.w50[html=Ebay<br/>margin-charge-qty]'),
                    new Element('th.brdCol.center.w50[html=EbayA<br/>margin-charge-qty]'),
                    new Element('th.brdCol.center.w50[html=Buy.com<br/>margin-charge-qty]')
                )
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[html=&nbsp;][colspan=11]')
                )
            ),
            new Element('tbody')
        );

        //
        this.epyVendorRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Loading...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('[' + resp + ']');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.fillContent(data);
            }.bind(this)
        }).send('table=epy&ex=getVends&nc=' + Date.now());

    },
    fillContent: function(data) {

        tbody = this.listData.getElement('tbody');
        tbody.empty();

        var vend,tbody,tr,color=false,tagid;
        for(var i = 0; i < data.length; i++) {
            vend = data[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'vnd_' + i;
            tbody.adopt(
                tr.adopt(
                    new Element('td.imgCol').adopt(
                        new Element('a.plus[html=&nbsp;][href=javascript:;][title=Open order]',{
                            'events': {
                                'click': this.openCategories.bind(this, vend.vid, tagid),
                                'focus': function() {this.blur();}
                            }
                        })
                    ),
                    new Element('td.imgCol').adopt(
                        new Element('a.edit[html=&nbsp;][href=javascript:;][title=Edit vendor]',{
                            'events': {
                                'click': this.editVendor.bind(this, vend.vid),
                                'focus': function() {this.blur();}
                            }
                        })
                    ),
                    new Element('td.imgCol').set('html','<a href="javascript:;" class="' + (vend.active ? 'check1': 'check0') + '">&nbsp;</a>'),
                    new Element('td.brdCol.center.w50[text=' + vend.als + ']'),
                    new Element('td.brdCol.w120[text=' + vend.name + ']'),
                    new Element('td.brdCol.left.w50[text=' + vend.cnt + ' - ' + vend.amazonSendQty + ' - ' + vend.amzcompSendQty + ' - ' + vend.ebaySendQty + ' - ' + vend.ebayAliSendQty + ' - ' + vend.buycomSendQty + ']'),
                    new Element('td.imgCol[html=' + ((vend.amazonMargin || vend.amazonCharge || vend.amazonQty) ? numberFormat(vend.amazonMargin) + '% - $' + numberFormat(vend.amazonCharge) + ' - ' + vend.amazonQty : '') + ']'),
                    new Element('td.imgCol[html=' + ((vend.amzcompMargin || vend.amzcompCharge || vend.amzcompQty) ? numberFormat(vend.amzcompMargin) + '% - $' + numberFormat(vend.amzcompCharge) + ' - ' + vend.amzcompQty : '') + ']'),
                    new Element('td.imgCol[html=' + ((vend.ebayMargin || vend.ebayCharge || vend.ebayQty) ? numberFormat(vend.ebayMargin) + '% - $' + numberFormat(vend.ebayCharge) + ' - ' + vend.ebayQty : '') + ']'),
                    new Element('td.imgCol[html=' + ((vend.ebayAliMargin || vend.ebayAliCharge || vend.ebayAliQty) ? numberFormat(vend.ebayAliMargin) + '% - $' + numberFormat(vend.ebayAliCharge) + ' - ' + vend.ebayAliQty : '') + ']'),
                    new Element('td.imgCol[html=' + ((vend.buycomMargin || vend.buycomCharge || vend.buycomQty) ? numberFormat(vend.buycomMargin) + '% - $' + numberFormat(vend.buycomCharge) + ' - ' + vend.buycomQty : '') +']')
                ),
                new Element('tr#x' + tagid + '[style=display:none]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=10][style=padding-top:0]')
                )
            );

        } // for

        this.listData.adopt(tbody);
    },
    openCategories: function(vendid, tagid, ev) {
        ev.stop();

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus');

            dcuc.empty();

            this.getVendorCategoriesRequest = new Request({
                url: '/Admin/webstat/getFromMySQL',
                method: 'get',
                onRequest: function() {
                    ev.target.addClass('load');
                    new ShowBox().say('Loading...');
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('[' + resp + ']');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    ev.target.removeClass('load');

                    this.showCategories(data, dcuc, vendid);
                }.bind(this)
            }).send('table=epy&ex=getVendCats&vid=' + vendid + '&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            ev.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }
    },
    showCategories: function(data, tag, vendid) {

        var tbody = new Element('tbody');
        var bid = 'vend_' + vendid;
        tag.adopt(
            new Element('table#listData', {'rules':'groups'}).adopt(
                new Element('thead').adopt(
                    new Element('tr').adopt(
                        new Element('th.brdCol.w120[text=Subcategory name]'),
                        new Element('th.brdCol.center.w50').adopt(
                            new Element('tt[text=Amazon]'),
                            new Element('br'),
                            new Element('input[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this, tag),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid + '_amz')
                        ),
                        new Element('th.brdCol.center.w50').adopt(
                            new Element('tt[text=AmzComp]'),
                            new Element('br'),
                            new Element('input[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this, tag),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid + '_amcp')
                        ),
                        new Element('th.brdCol.center.w50').adopt(
                            new Element('tt[text=Ebay]'),
                            new Element('br'),
                            new Element('input[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this, tag),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid + '_eby')
                        ),
                        new Element('th.brdCol.center.w50').adopt(
                            new Element('tt[text=EbayA]'),
                            new Element('br'),
                            new Element('input[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this, tag),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid + '_ebya')
                        ),
                        new Element('th.brdCol.center.w50').adopt(
                            new Element('tt[text=Buy.com]'),
                            new Element('br'),
                            new Element('input[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this, tag),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid + '_buy')
                        )
                    )
                ),
                new Element('tfoot').adopt(
                    new Element('tr').adopt(
                        new Element('th.brdCol.center.w50').adopt(
                            new  Element('button[text=Save ]',{
                                'events': {
                                    'click': this.saveVendSubcategory.bind(this, tag, vendid),
                                    'focus': function() {this.blur();}
                                }
                            }).store('vend', bid)
                        ),
                        new Element('th.tdFull[html=&nbsp;][colspan=6]')
                    )
                ),
                tbody
            )
        );

        var cat,tr,color=false;
        for(var i = 0; i < data.length; i++) {
            cat = data[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tbody.adopt(
                tr.adopt(
                    new Element('td.brdCol.w120[text=' +cat.name + ' (' + cat.cnt + ')]'),
                    new Element('td.brdCol.center.w50').set('html','<input id="' + bid + '_amz" '  + (cat.amazonSend ? 'checked="checked"': '' )  + ' value="amz" name="' + cat.cid + '" type="checkbox"/>'),
                    new Element('td.brdCol.center.w50').set('html','<input id="' + bid + '_amcp" ' + (cat.amzcompSend ? 'checked="checked"': '' ) + ' value="amcp" name="' + cat.cid + '" type="checkbox"/>'),
                    new Element('td.brdCol.center.w50').set('html','<input id="' + bid + '_eby" '  + (cat.ebaySend ? 'checked="checked"': '' )    + ' value="eby" name="' + cat.cid + '" type="checkbox"/>'),
                    new Element('td.brdCol.center.w50').set('html','<input id="' + bid + '_ebya" ' + (cat.ebayAliSend ? 'checked="checked"': '' ) + ' value="ebya" name="' + cat.cid + '" type="checkbox"/>'),
                    new Element('td.brdCol.center.w50').set('html','<input id="' + bid + '_buy" '  + (cat.buycomSend ? 'checked="checked"': '' )  + ' value="buy" name="' + cat.cid + '" type="checkbox"/>')
                )
            );
        } // for


    },
    groupToggle: function(tag, ev) {
        var docheck = ev.target.get('checked');
        var checkme = tag.getElements('input[id=' + ev.target.retrieve('vend') + ']');
        checkme.each(function(el) {
            el.set('checked', docheck);
        });
    },
    hashString: function(hash, vendid) {
        var resul = '', idx = 0;
        hash.each(function(val, key) {
            resul += (idx++ > 0 ? ':' : '') + vendid + ',' + key + ',' + val;
        });
        return resul;
    },
    saveVendSubcategory: function(tag, vendid, ev) {
        ev.stop();
        var checkme = tag.getElements('input[id^=' + ev.target.retrieve('vend') + ']');
        var hash = new Hash(),pos;
        checkme.each(function(el) {
            pos = [,,];
            if(hash.has(el.get('name'))) {
                pos = hash.get(el.get('name'));
                if(el.get('value') == 'amz')        pos[0] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'amcp')  pos[1] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'eby')   pos[2] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'ebya')  pos[3] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'buy')   pos[4] = el.get('checked') ? 1:0;
                hash.set(el.get('name'), pos);
            }
            else {
                if(el.get('value') == 'amz')        pos[0] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'amcp')  pos[1] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'eby')   pos[2] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'ebya')  pos[3] = el.get('checked') ? 1:0;
                else if(el.get('value') == 'buy')   pos[4] = el.get('checked') ? 1:0;
                hash.set(el.get('name'), pos);
            }
        });
        var parms = '&cb=' + this.hashString(hash,vendid);

        this.saveRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Saving...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=epy&ex=saveVendCats' + '&nc=' + Date.now() + parms);

    },
    editVendor: function(vendid, ev) {
        ev.stop();
        new EditVendor({
            'vendid': vendid,
            'targetid': ev.target,
            'onReload': function() {

                this.epyVendorRequest.send('table=epy&ex=getVends&nc=' + Date.now());
            }.bind(this)
        });
    }
});

var EditVendor = new Class({
    Implements: [Events, Options],
    options: {
        vendid: 0,
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);
        if(!this.options.vendid) return;

        // fill box
        this.vendchange = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                this.options.targetid.removeClass('edit').addClass('load');
            }.bind(this),
            onComplete: function(resp) {
                this.options.targetid.removeClass('load').addClass('edit');

                this.makeForm(resp);
            }.bind(this)
        }).send('table=epy&ex=getVend&vid=' + this.options.vendid + '&nc=' + Date.now());

    },
    makeForm: function(resp) {
        if(!resp.length) return;
        var vend = eval('(' + resp + ')');

        this.active = new Element('input[name=active][type=checkbox]').set('checked', vend.active);
        this.update = new Element('a.update.closeThis[html=&nbsp;][href=javascript:;][title=Update Vendor]');

        this.table = new Element('table#ggroup[style=border-spacing:5px;border-collapse:separate;]').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('th[html=&nbsp;]'),
                    new Element('th[text=Margin %]'),
                    new Element('th[text=subCharge $]'),
                    new Element('th[text=subQty]')
                ),
                new Element('tr').adopt(
                    new Element('th.right[text=Amazon]'),
                    new Element('th',{'html':'<input name="amazonMargin" value="' + (vend.amazonMargin != '0.00' ? vend.amazonMargin : '' ) + '" size=6 maxlength=3 type="text"/>'}),
                    new Element('th',{'html':'<input name="amazonCharge" value="' + (vend.amazonCharge != '0.00' ? vend.amazonCharge : '' ) + '" size=6 maxlength=10 type="text"/>'}),
                    new Element('th',{'html':'<input name="amazonQty" value="' + (vend.amazonQty ? vend.amazonQty : '' ) + '" size=6 maxlength=3 type="text"/>'})
                ),
                new Element('tr').adopt(
                    new Element('th.right[text=AmzComp]'),
                    new Element('th',{'html':'<input name="amzcompMargin" value="' + (vend.amzcompMargin != '0.00' ? vend.amzcompMargin : '' ) + '" size=6 maxlength=3 type="text"/>'}),
                    new Element('th',{'html':'<input name="amzcompCharge" value="' + (vend.amzcompCharge != '0.00' ? vend.amzcompCharge : '' ) + '" size=6 maxlength=10 type="text"/>'}),
                    new Element('th',{'html':'<input name="amzcompQty" value="' + (vend.amzcompQty ? vend.amzcompQty : '' ) + '" size=6 maxlength=3 type="text"/>'})
                ),
                new Element('tr').adopt(
                    new Element('th.right[text=Ebay]'),
                    new Element('th',{'html':'<input name="ebayMargin" value="' + (vend.ebayMargin != '0.00' ? vend.ebayMargin : '' ) + '" size=6 maxlength=3 type="text"/>'}),
                    new Element('th',{'html':'<input name="ebayCharge" value="' + (vend.ebayCharge != '0.00' ? vend.ebayCharge : '' ) + '" size=6 maxlength=10 type="text"/>'}),
                    new Element('th',{'html':'<input name="ebayQty" value="' + (vend.ebayQty ? vend.ebayQty : '' ) + '" size=6 maxlength=3 type="text"/>'})
                ),
                new Element('tr').adopt(
                    new Element('th.right[text=EbayA]'),
                    new Element('th',{'html':'<input name="ebayAliMargin" value="' + (vend.ebayAliMargin != '0.00' ? vend.ebayAliMargin : '' ) + '" size=6 maxlength=3 type="text"/>'}),
                    new Element('th',{'html':'<input name="ebayAliCharge" value="' + (vend.ebayAliCharge != '0.00' ? vend.ebayAliCharge : '' ) + '" size=6 maxlength=10 type="text"/>'}),
                    new Element('th',{'html':'<input name="ebayAliQty" value="' + (vend.ebayAliQty ? vend.ebayAliQty : '' ) + '" size=6 maxlength=3 type="text"/>'})
                ),
                new Element('tr').adopt(
                    new Element('th.right[text=Buy.com]'),
                    new Element('th',{'html':'<input name="buycomMargin" value="' + (vend.buycomMargin != '0.00' ? vend.buycomMargin : '' ) + '" size=6 maxlength=3 type="text"/>'}),
                    new Element('th',{'html':'<input name="buycomCharge" value="' + (vend.buycomCharge != '0.00' ? vend.buycomCharge : '' ) + '" size=6 maxlength=10 type="text"/>'}),
                    new Element('th',{'html':'<input name="buycomQty" value="' + (vend.buycomQty ? vend.buycomQty : '' ) + '" size=6 maxlength=3 type="text"/>'})
                ),
                new Element('tr').adopt(
                    new Element('td.col[colspan=2]').adopt(
                        this.active,
                        new Element('em[text=Active]')
                    ),
                    new Element('td.col[colspan=2]').adopt(
                        this.update,
                        new Element('em[text=Update]')
                    )
                )
            )
        );

        new ModalBox({
            width: 350,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.update.addEvents({'click': this.updateVendor.bind(this, vend.vid), 'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Vendor: ' + vend.name + '</h2>', new Element('center').adopt(this.table));


    },
    updateVendor: function(vendid) {

        var inps = this.table.getElements('input'), parms = '&cb=', tag;
        for(var i = 0; i < inps.length; i++) {
            tag = inps[i];
            parms += tag.get('name') + '_' + (tag.get('type') == 'text' ? (tag.get('value') ? tag.get('value'): 0) : (tag.get('checked') ? 1: 0) ) + '_';
        }

        this.vendupdate = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Save...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=epy&ex=updVend&vid=' + vendid + '&nc=' + Date.now() + parms);

        this.fireEvent('reload');
    }
});
